<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chat-one</title>
</head>
<script>
    //var id = Math.random().toString(36).substr(2);
    var id;
    var socket;
    if (window.WebSocket) {
        socket = new WebSocket('ws://127.0.0.1:9899/ws');
        socket.onmessage = function (ev) {
            var rt = document.getElementById('responseText');
            rt.value = rt.value + '\n\n' + ev.data;
        }

        socket.onopen = function (ev) { // open
            var rt = document.getElementById('responseText');
            rt.value = '连接开启了...';
            id = document.getElementById('sendUser').value;
            registerUser();
        }
        socket.onclose = function (ev) { // close
            var rt = document.getElementById('responseText');
            rt.value = rt.value + '\n' + '连接关闭了...';
        }
    } else {
        alert('当前浏览器不支持webSocket');
    }

    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == window.WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert('连接没有开启');
        }
    }

    function sendMsg(msg) {
        var sendTo = document.getElementById('sendTo').value;
        var options = {
            'id': id,
            'sendTo': sendTo,
            'msg': msg
        };
        var op = JSON.stringify(options);
        socket.send(op);
    }

    /**
     * 注册用户
     */
    function registerUser() {
        var options = {
            "id": id,
            "type": "single"
        };
        var op = JSON.stringify(options);
        socket.send(op);
    }

</script>
<body>
<script src="./jquery/jquery.min.js"></script>
发送方：<input id="sendUser" value="li4"/><br/>
发送给：<input id="sendTo" value="zhang3"/>
<hr/>
<form onsubmit="return false">
    <textarea name="message" style="height: 300px;width: 300px;"></textarea>
    <input type="button" value="发送消息" onclick="sendMsg(this.form.message.value)"/>
    <textarea id="responseText" style="height: 300px;width: 500px;"></textarea>
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''"/>
</form>

</body>
</html>